package entities;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import data.enums.ArchiveDescription;
import data.enums.Folder;
import data.enums.TableType;
import entities.box_plot.TableMlpTestsOneIndexByContinent;

/**
 * K = Class of columns
 */
public abstract class AbstractTable <K> {

	private TableType type;
	
	protected Map<K, List<BigDecimal>> table = new HashMap<>();
	protected ArchiveDescription description;
	 
	public AbstractTable(TableMlpTestsOneIndexByContinent tableMlp, ArchiveDescription description, TableType type) {
		this.description = description;
		this.type = type;
		initializeTable(tableMlp);
	}
	
	public void addRow (K columnValue, BigDecimal performance) {
		
		if (this.table.get(columnValue) != null) {
			this.table.get(columnValue).add(performance);
		} else {
			this.table.put(columnValue, new ArrayList<BigDecimal>(Arrays.asList(performance)));
		}
		
	}
	
	public void saveTableAsTxt() throws IOException {

		PrintWriter writer = new PrintWriter(new FileWriter(new File(Folder.ONE_INDEX_BY_CONTINENT_OUTPUT + type.toString() + description + ".txt")));

		writer.println(getHeader());

		Set<K> orderedKeys = new TreeSet<>(table.keySet());
		Iterator<K> it = orderedKeys.iterator();

		if (it.hasNext()) {

			K first = it.next();

			// considering all List with the same size
			for (int i = 0; i < table.get(first).size(); i++) {

				for (K k : orderedKeys) {

					writer.print(((BigDecimal) table.get(k).get(i)).setScale(2, BigDecimal.ROUND_FLOOR) + "\t");

				}

				writer.println();
			}
		}

		writer.flush();
		writer.close();
	}
	
	public String getHeader() {

		StringBuilder string = new StringBuilder();

		Set<K> orderedKeys = new TreeSet<>(table.keySet());

		for (K k : orderedKeys) {
			string.append(k).append("\t");
		}

		return string.toString();
		
	}
	
	protected abstract void initializeTable(TableMlpTestsOneIndexByContinent tableMlp);
	
}
